import fs from 'fs';

// 读取 GeoJSON 文件
const geojsonFile = './shangluo-all.json';
const geojsonData = JSON.parse(fs.readFileSync(geojsonFile, 'utf8'));

// 准备级联选择器数据
function parseGeojson(data) {
    const provinces = {};
    const cities = {};
    const districts = {};
    const towns = {};

    data.features.forEach(feature => {
        const { province, city, country: district, name: town } = feature.properties;

        if (!provinces[province]) {
            provinces[province] = { value: province, label: province, children: [] };
        }
        if (!cities[city]) {
            cities[city] = { value: city, label: city, children: [] };
            provinces[province].children.push(cities[city]);
        }
        if (!districts[district]) {
            districts[district] = { value: district, label: district, children: [] };
            cities[city].children.push(districts[district]);
        }
        if (!towns[town]) {
            towns[town] = { value: town, label: town };
            districts[district].children.push(towns[town]);
        }
    });

    return Object.values(provinces);
}

// 将数据保存到 JSON 文件
function saveToJson(data, filename) {
    fs.writeFileSync(filename, JSON.stringify(data, null, 2), 'utf8');
}

// 主函数
const cascaderData = parseGeojson(geojsonData);
const outputFile = 'addressData.json';
saveToJson(cascaderData, outputFile);

console.log(`Data has been saved to ${outputFile}`);
